import { defineStore } from 'pinia'
import { Category, CategoryDTO, Tag } from './data'
import { deleteCategories, getCategories, getTags, putCategory } from './service'
import { ref, shallowRef } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useDefaultRef } from '@/hooks/useDefaultRef'

export const useCategoriesStore = defineStore('categories', () => {
  const items = shallowRef<Category[]>([])

  const total = ref(0)

  const current = ref(1)

  const onGet = async () => {
    const data = await getCategories({ current: current.value })
    items.value = data.records
    total.value = data.total
  }

  const search = ref('')

  const onSearch = async () => {
    const data = await getCategories({ current: (current.value = 1), name: search.value })
    items.value = data.records
    total.value = data.total
  }

  const onResetSearch = () => ((search.value = ''), onGet())

  const [form, onResetForm] = useDefaultRef<{
    on: boolean
    allTags: Tag[]
    id: CategoryDTO.Put['id']
    items: Pick<CategoryDTO.Put, 'name' | 'description' | 'tagIdList'>
  }>(() => ({
    on: false,
    allTags: [],
    id: void 0,
    items: {
      name: '',
      description: '',
      tagIdList: [],
    },
  }))

  const onInitForm = async (dto?: Required<Pick<CategoryDTO.Put, 'id' | 'name' | 'description' | 'tagIdList'>>) => {
    form.value.allTags = await getTags()
    if (dto) {
      const { id, name, description, tagIdList } = dto
      form.value.id = id
      form.value.items = { name, description, tagIdList }
    }
    form.value.on = true
  }

  const onSubmitPut = async () => {
    const { name, tagIdList, description } = form.value.items
    const dto: CategoryDTO.Put = { name, tagIdList, description }
    if (form.value.id) dto.id = form.value.id
    if (name?.trim()) {
      await putCategory(dto)
      onGet()
      onResetForm()
    }
  }

  const onDelete = async (row: Category) => {
    try {
      await ElMessageBox.confirm(`确定删除该分类: ${row.name} ？`, { title: '删除分类', type: 'error' })
      await deleteCategories([row.id])
      items.value = items.value.filter(({ id }) => id !== row.id)
    } catch {
      console.warn(`取消删除`)
    }
  }

  const selection = ref<Category[]>([])

  const onBatchDelete = async () => {
    try {
      if (selection.value.length > 0) {
        await ElMessageBox.confirm(`以下分类将被删除：${selection.value.map(({ name }) => name).join('，')} ，确认？`, {
          title: '批量删除',
          type: 'error',
        })
        await deleteCategories(selection.value.map(({ id }) => id))
        items.value = items.value.filter((item) => selection.value.some(({ id }) => item.id === id))
      }
    } catch {
      console.warn(`取消删除`)
    }
  }

  return {
    items,
    total,
    current,
    onGet,
    search,
    onSearch,
    onResetSearch,
    form,
    onResetForm,
    onInitForm,
    onSubmitPut,
    onDelete,
    selection,
    onBatchDelete,
  }
})
